#!/usr/bin/env bash
# tovid demo script

# ========================================================================
# Global constants
# Working directories
DEMO_HOME=tovid_demo
DEMO_LOG="$DEMO_HOME/tovid-demo.log"
BIN=$DEMO_HOME/bin
VIDS=$DEMO_HOME/vids

# ========================================================================
# Function definitions

# get_source_file
# Download a source file from the internet, and set it +x
# Sources are saved to $BIN
#
# Example:
#   Retrieve http://foobar.org/baz.sh with:
#   get_source_file http://foobar.org baz.sh
function get_source_file()
{
    URL="$1"
    SRC="$2"
    if wget "$URL/$SRC" --output-document="$BIN/$SRC" >> $DEMO_LOG 2>&1; then :
    else
        runtime_fail "Problem downloading $SRC!"
    fi
    chmod +x $BIN/$SRC
}


# get_youtube_vid
# Download a video from YouTube
# Videos are saved to $VIDS with the given name ('.flv' is added)
# Videos are NOT re-downloaded if the given name exists already (time saver).
#
# Example:
#   Retrieve http://youtube.com/watch?v=JzqumbhfxRo as "amateur.flv" with:
#   get_youtube_vid http://youtube.com/watch?v=JzqumbhfxRo amateur
function get_youtube_vid()
{
    URL="$1"
    NAME="$2"
    if ! test -f "$VIDS/$NAME.flv"; then
        if youtube-dl -o "$VIDS/$NAME.flv" "$URL" >> $DEMO_LOG 2>&1; then :
        else
            runtime_fail "Problem downloading $URL!"
        fi
    else
        echo "$VIDS/$NAME.flv already downloaded"
    fi
}


# runtime_fail
# Exit the demo, with an optional help message
#
# Example:
#   runtime_fail "Problem downloading a file!"
function runtime_fail()
{
    MSG="$1"
    echo -e "\n\n$MSG"
    echo "Please keep the file $DEMO_LOG and go to tovid.org for help."
    echo "Exiting..."
    exit 1
}

# ========================================================================
# Basic set-up/checks

# Empty the log file
echo -n > "$DEMO_LOG"

# Make the destination directories if they don't exist already
for dir in $DEMO_HOME $BIN $VIDS; do
    if ! test -d $dir; then
        mkdir $dir
    fi
done

# Check for run-time deps
DEPS="wget python sed grep awk ffmpeg mplayer mencoder mplex mpeg2enc yuvfps yuvdenoise ppmtoy4m mp2enc jpeg2yuv composite convert mogrify montage identify dvdauthor spumux growisofs tcprobe tcdemux transcode"
# Determine if any group member is missing
NO_GROUP=false
for dep in $DEPS; do
    if ! type -a $dep >> $DEMO_LOG 2>&1; then
        printf "%-13s %s\n" "  $dep" "MISSING!"
        NO_GROUP=:
    fi
done
# Quit if any group member is missing
if $NO_GROUP; then
    echo
    echo "Sorry! You can't run the demo until these packages are installed."
    exit 1
fi

# Greeting
GREETING=`cat << EOF

/======================== T O V I D   D E M O ===========================\\\\
  Hi! Thanks for downloading the tovid demo. Please sit back, relax, 
  and wait while everything sorts itself out. In the end, you'll have a 
  working DVD image. (ready to burn!)

  I'll be downloading the latest tovid development version, some helper 
  files, and a few videos from YouTube to make the DVD. I'll convert 
  the YouTube videos, make an animated menu, and create the DVD image.

  Please be patient. . . This may take 1-2 hours.

  While you're waiting, consider coming by the irc channel '#tovid' on
  chat.freenode.net to say hello!
\\\\========================================================================/

EOF`
echo "$GREETING"

# ========================================================================
# Get executables

echo
echo "Grabbing the latest scripts..."

# tovid sources
# =============
TOVID_DL_HOME="http://tovid.googlecode.com/svn/trunk/tovid/src/"
TOVID_SRCS="idvid tovid makedvd todisc todisc-fade-routine tovid-init.in"

echo     "   tovid sources:"
echo     "      $TOVID_SRCS"
echo -n  "      "
for src in $TOVID_SRCS; do
    get_source_file $TOVID_DL_HOME $src
    echo -n "$src "
done
echo

# Update executable path
PATH="$PWD/$BIN:$PATH"
export PATH

# Set version
DEMO_VERSION=$(wget --quiet http://tovid.googlecode.com/svn/trunk/tovid/ -O - |
awk  '/Revision/ {print $2}' |awk -F: 'END{print $1}')
sed -i "s/@VERSION@/demo-$DEMO_VERSION/" $BIN/tovid-init.in
mv $BIN/tovid-init.in $BIN/tovid-init

# Get YouTube video downloader
# ============================
YGET_DL_HOME="http://bitbucket.org/rg3/youtube-dl/raw/2010.03.13/"
YGET="youtube-dl"

echo -n "   youtube-dl...   "
get_source_file $YGET_DL_HOME $YGET
echo "done."

# ========================================================================
# Get DVD source video/images/sound

echo
echo "Grabbing the background image and audio for the main menu... (4MB)"

# Menu background image
MENU_BG_SRC="http://farm1.static.flickr.com/126/336686002_4b3cb2fa65_b_d.jpg"
MENU_BG="sunset.jpg"
MENU_BG_STR="$MENU_BG from technicolorcavalry on flickr.com"
printf "   %s: %-55s" "Image" "$MENU_BG_STR..."
if ! test -f $VIDS/$MENU_BG; then
    if ! wget "$MENU_BG_SRC" -O "$VIDS/$MENU_BG" >> $DEMO_LOG 2>&1; then 
        runtime_fail "Couldn't get background image ($MENU_BG_SRC)!"
    fi
fi
echo "done."

# Menu audio
MENU_AUD_SRC="http://ccmixter.org/content/paulosacramento/paulosacramento_-_Batida_Urbana.mp3"
MENU_AUD="batida-urbana.mp3"
MENU_AUD_STR="Batida Urbana by Paulo Sacramento on opsound.org"
printf "   %s: %-55s" "Audio" "$MENU_AUD_STR..."
if ! test -f $VIDS/$MENU_AUD; then
    if ! wget "$MENU_AUD_SRC" -O "$VIDS/$MENU_AUD" >> $DEMO_LOG 2>&1; then
        runtime_fail "Couldn't get menu audio ($MENU_AUD_SRC)!"
    fi
fi
echo done.

# Demo videos
VID_1_SRC="http://youtube.com/watch?v=7doO_S5iZP0"
VID_1_NAME="poppin"
VID_1_STR="Poppin' in the Streets of Korea"

VID_2_SRC="http://youtube.com/watch?v=JzqumbhfxRo"
VID_2_NAME="amateur"
VID_2_STR="Amateur by Lasse Gjertsen"

VID_3_SRC="http://youtube.com/watch?v=N5XVeENmLMk"
VID_3_NAME="fujiya"
VID_3_STR="Fujiya & Miyagi - Ankle Injuries"

VID_4_SRC="http://youtube.com/watch?v=v4Wy7gRGgeA"
VID_4_NAME="monkey"
VID_4_STR="Code Monkey music video"

echo
echo "Grabbing 4 YouTube videos (34MB). Give me about 10 minutes..."

i=1
for vid in "$VID_1_SRC,$VID_1_NAME,$VID_1_STR" \
           "$VID_2_SRC,$VID_2_NAME,$VID_2_STR" \
           "$VID_3_SRC,$VID_3_NAME,$VID_3_STR" \
           "$VID_4_SRC,$VID_4_NAME,$VID_4_STR"; do
    url=$(echo $vid | awk -F "," '{print $1}')
    name=$(echo $vid | awk -F "," '{print $2}')
    str=$(echo $vid | awk -F ',' '{print $3}')
    printf "   %s: %-38s" "$i" "$str..."
    get_youtube_vid $url $name
    echo "done."
    i=$(expr $i \+ 1)
done

# ========================================================================
# Convert the demo videos
echo
echo "Converting videos to DVD specification. Give me about 12 minutes..."

i=1
for vid in "$VID_1_SRC,$VID_1_NAME,$VID_1_STR" \
           "$VID_2_SRC,$VID_2_NAME,$VID_2_STR" \
           "$VID_3_SRC,$VID_3_NAME,$VID_3_STR" \
           "$VID_4_SRC,$VID_4_NAME,$VID_4_STR"; do
    url=$(echo $vid | awk -F "," '{print $1}')
    name=$(echo $vid | awk -F "," '{print $2}')
    str=$(echo $vid | awk -F ',' '{print $3}')
    printf "   %s: %-38s" "$i" "$str..."
    if ! test -f "$VIDS/$name.mpg"; then
        if ! tovid -noask -ffmpeg -in $VIDS/$name.flv -out $VIDS/$name >> $DEMO_LOG 2>&1; then
            runtime_fail "Couldn't encode $name.flv!"
        fi
    fi
    echo "done."
    i=$(expr $i \+ 1)
done

# ========================================================================
# Author the disc
IMAGE="tovid_demo_DVD"
echo
echo "Making the menu and DVD image. Give me about 40 minutes..."
if ! test -d $IMAGE; then
    if ! tovid disc -files $VIDS/*.mpg -titles "Amateur" "Ankle Injuries" "Code Monkey" "Korean Breakers" -background $VIDS/$MENU_BG -bgaudio $VIDS/$MENU_AUD -menu-title "tovid demo DVD" -menu-fade -thumb-shape normal -noask -button-style rect -text-mist -out "$IMAGE" >> $DEMO_LOG 2>&1; then
    runtime_fail "Could't make DVD image!"
    fi
fi

# ========================================================================
# Sign off

GOODBYE=`cat << EOF

/========================== F I N I S H E D =============================\\\\
  Well, it looks like I'm all done here. You can preview your dvd with:

        gxine "dvd:/$PWD/$IMAGE"
        or: vlc "$PWD/$IMAGE"

  And you can burn it with:

        export PATH="$PWD/$BIN:\\$PATH"
        makedvd -burn $IMAGE

  Thanks for trying the tovid demo. We hope you like what you see!
  We're at http://tovid.org if you have feedback or questions.
\\\\========================================================================/

EOF`

echo "$GOODBYE"
rm todisc.log >> $DEMO_LOG 2>&1
exit 0
